#include "bird.h"
#include <QPainter>
#include <QDebug>
#include <QGraphicsScene>
#include <QGraphicsView>
#include "Define.h"

qreal myEasingFunction(qreal progress)//自定义曲线函数，用于小鸟上下飞行的动画效果
{
    return -BIRD_JUMP*(progress*progress-0.5*progress);
}

Bird::Bird()
{
    status = 0;
    m_anim.setTargetObject(this);
    m_anim.setPropertyName("pos");

    m_timer = new QTimer(this);
    connect(m_timer,SIGNAL(timeout()),this,SLOT(changeStatus()));//连接计时器的timeout()信号和改变状态的槽函数

    m_checkTimer = new QTimer(this);
    connect(m_checkTimer,SIGNAL(timeout()),this,SLOT(checkCollision()));//连接碰撞检测定时器的timeout()信号和检测碰撞的槽函数
    m_checkTimer->start(20); //定时器开始计时
    m_checkTimer->start(20);
    isDied = false;
}

QRectF Bird::boundingRect() const
{
    return  BIRD_BOUNDING;//绘制边界框
}

void Bird::paint( QPainter* pPainter,
                        const QStyleOptionGraphicsItem* pOption,
                        QWidget* pWidget )
{
    Q_UNUSED(pOption);
    Q_UNUSED(pWidget);
    QPixmap src(":/hero_1.png");//加载小鸟图
    pPainter->drawPixmap(BIRD_BOUNDING,//绘制小鸟图像到画家上下文中
                         src.copy(src.width()/4*status,src.height()/2,src.width()/4,src.height()/4),
                         QRectF(5,5,src.width()/4-20,src.height()/4-20 ));
    //绘制边界框
}

void Bird::ClickToFlay()//处理小鸟点击屏幕屏幕事件（开始飞翔）
{
    if(isDied)
        return;
    m_anim.stop();
    m_anim.setDuration(BIRD_FLAYTIME);
    m_anim.setStartValue(this->pos());
    m_anim.setEndValue(this->pos()+QPoint(0,-20));//上移20个像素
    m_curve.setCustomType(myEasingFunction);
    m_anim.setEasingCurve(m_curve);//设置动画缓和曲线函数
    m_anim.start();//小鸟开始飞翔的动画效果

    m_timer->start(BIRD_FLAYTIME/8);//煽动翅膀的计时器开始工作
    status = 0;
}

void Bird::changeStatus() //检测状态
{
    status ++;
    this->scene()->views().value(0)->repaint();
    if(status == 3)
    {
        m_timer->stop();
    }
}

void Bird::checkCollision() //检测碰撞
{
    if(this->collidingItems().size()!=0)
    {//同一场景item碰撞数量
        CollisionToDeath();
    }
}

void Bird::CollisionToDeath()//碰撞并死亡
{
    m_timer->stop(); //停止煽动翅膀的计时器
    m_checkTimer->stop();//停止碰撞检测定时器
    status = 3;//设置小鸟状态为3（煽动翅膀的最后一个状态）
    this->scene()->views().value(0)->repaint();//刷新画面
    m_anim.stop(); //停止当前小鸟动画
    m_anim.setDuration(DEATH_TIME);//设置小鸟死亡动画时长
    m_anim.setStartValue(this->pos());
    m_anim.setEndValue(this->pos()+QPoint(0,600));//向下移动600像素
    m_anim.start();//开始动画
    isDied = true;//标志小鸟已死亡
    emit died(); //发送小鸟死亡信号
}

void Bird::reBegin()//重新开始游戏
{
    m_anim.stop();//停止小鸟动画
    m_checkTimer->start();//开始碰撞检测计时器
    status = 0;//初始化小鸟的状态为0
    isDied = false;//标志小鸟存活
    this->scene()->views().value(0)->repaint();//刷新画面
}
